<template>
  <div class="my-projectForm basic-from">
    <v-dialog :title="isAdd ? '新增' : '编辑'" :show.sync="dialogVisible" width="1200px" @beforeClose="beforeClose" :close-on-click-modal="false">
      <!-- <div class="card-box"> -->
      <div class="card-title">工程信息</div>
      <el-form ref="information" :model="projectForm.information" class="form-wrap" size="small" :rules="information_rules" label-position="top">
        <el-form-item label="工程名称" prop="projectName">
          <el-input v-halfCharCode v-model="projectForm.information.projectName" maxlength="50" placeholder="请输入工程名称" />
        </el-form-item>
        <el-form-item label="工程地址" prop="projectAddress">
          <el-input v-halfCharCode v-model="projectForm.information.projectAddress" maxlength="50" placeholder="请输入工程地址" />
        </el-form-item>
        <el-form-item label="工程类型" prop="projectType">
          <el-select clearable v-model="projectForm.information.projectType" placeholder="请选择工程类型">
            <el-option v-for="item in projectTypes" :key="item.label" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建设内容" class="full" prop="projectContent">
          <el-input v-halfCharCode v-model="projectForm.information.projectContent" maxlength="300" placeholder="请输入建设内容" />
        </el-form-item>
        <el-form-item label="建设规模" class="full" prop="projectScale">
          <el-input v-halfCharCode v-model="projectForm.information.projectScale" maxlength="300" placeholder="请输入建设规模" />
        </el-form-item>
        <el-form-item label="工程建设工期" prop="projectStart">
          <el-date-picker type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" v-model.trim="projectForm.information.projectStart" format="yyyy-MM-dd" valueFormat="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
        <el-form-item label="资金来源" prop="projectSource">
          <el-input v-halfCharCode v-model="projectForm.information.projectSource" maxlength="50" placeholder="请输入资金来源" />
        </el-form-item>
        <el-form-item label="建筑面积" prop="buildArea">
          <el-input v-halfCharCode v-model="projectForm.information.buildArea" maxlength="50" placeholder="请输入建筑面积" />
        </el-form-item>
<!--        <el-form-item label="装修面积" prop="decorationArea">建筑面积=关联物业面积总和-->
<!--          <el-input v-halfCharCode v-model="projectForm.information.decorationArea" maxlength="50" placeholder="请输入装修面积" />-->
<!--        </el-form-item>-->
        <el-form-item label="意见" class="full" prop="remarks">
          <el-input v-halfCharCode v-model="projectForm.information.remarks" maxlength="500" placeholder="请输入意见" />
        </el-form-item>
      </el-form>
      <div class="card-title">代建单位信息</div>
      <el-form ref="agentUnit" :model="projectForm.agentUnit" class="form-wrap" size="small" :rules="agentUnit_rules" label-position="top">
        <el-form-item label="代建单位" prop="agentInfo">
          <el-input v-halfCharCode v-model="projectForm.agentUnit.agentInfo" maxlength="50" placeholder="请输入代建单位" />
        </el-form-item>
        <el-form-item label="单位联系人" prop="agentContact">
          <el-input v-halfCharCode v-model="projectForm.agentUnit.agentContact" maxlength="30" placeholder="请输入单位联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="agentPhone">
          <el-input v-halfCharCode v-model="projectForm.agentUnit.agentPhone" maxlength="20" placeholder="请输入联系手机或座机号码" />
        </el-form-item>
      </el-form>
      <div class="card-title">代建单位中标通知书信息</div>
      <el-form ref="winningBid" :model="projectForm.winningBid" class="form-wrap" size="small" :rules="winningBid_rules" label-position="top">
        <el-form-item label="中标通知书文号" prop="bidDocument">
          <el-input v-halfCharCode v-model="projectForm.winningBid.bidDocument" maxlength="50" placeholder="请输入中标通知书文号" />
        </el-form-item>
        <el-form-item label="金额(元)" prop="bidAmount">
          <el-input v-halfCharCode v-model="projectForm.winningBid.bidAmount" maxlength="20" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="审批日期" prop="bidApprove">
          <el-date-picker v-model="projectForm.winningBid.bidApprove" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="请选择审批日期"></el-date-picker>
        </el-form-item>
      </el-form>
      <div class="card-title">
        关联物业信息
        <span>
          <el-button class="add-property" size="mini" type="primary" @click="handleAddProperty">添加物业</el-button>
        </span>
      </div>
      <div class="handling-opinions" style="padding:10px 0 0">
        <el-table :data="tableData">
          <el-table-column label="项目名称" prop="projectName" />
          <el-table-column label="物业名称" prop="propertyName" />
          <el-table-column label="建筑面积" prop="buildingArea" />
          <el-table-column label="套内面积" prop="unitConstructionArea" />
          <el-table-column label="物业类型" prop="projectType">
            <template slot-scope="scope">{{getCardTypeValue(scope.row.projectType,projectTypeList)}}</template>
          </el-table-column>
          <el-table-column label="物业用途" prop="projectSubclassType">
            <template slot-scope="scope">{{getCardTypeValue(scope.row.projectSubclassType,projectSubclassTypeList)}}</template>
          </el-table-column>
          <el-table-column label="操作" align="left">
            <template slot-scope="scope">
              <el-button type="text" @click="handleDeleteProperty(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="card-title">附件</div>
      <div class="handling-opinions">
        <v-upload ref="registrationUpload" :busId="projectForm.information.projectId" modelType="registration" @onSuccess="onSuccess" isShowFileList :isView="false" multiple v-model="fileList" />
      </div>
      <!--        工程弹框-->
      <choose-dialog ref="chooseDialog" v-bind="chooseDialogAttrs" @chooseData="handleClickAdd" />
      <!-- </div> -->
      <span slot="foot">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button v-throttle="[commit]">保 存</el-button>
      </span>
    </v-dialog>
  </div>
</template>

<script>
import BaseLoad from '@/assets/vue-mixin/BaseLoad'
import { doubleValidate, validatePhoneTwo } from '~/utils/validate.js'
import { save, update, get, validateBidDocument, validateName } from '../api/registration'
import { calc } from '@/utils'
export default {
  name: "edit-data",
  created () {
    this.projectTypes = this.getDict('epc_project_type')
    this.projectTypeList = this.getDict('property_types')
    this.projectSubclassTypeList = this.getDict('property_use_types')
  },
  mixins: [BaseLoad],
  data () {
    let validateBidDo = (rule, value, callback) => {
      if (!value) {
        callback()
      }
      this.validateOnly(value, callback)
    };
    let validateProjectName = (rule, value, callback) => {
      if (!value) {
        callback()
      }
      this.validateNameOnly(value, callback)
    };
    return {
      dialogVisible: false,
      isAdd: true,
      projectForm: {
        information: {
          projectId: '',
          projectName: '',
          projectAddress: '',
          projectType: '',
          projectContent: '',
          projectScale: '',
          projectStart: '',
          projectEnd: '',
          projectSource: '',
          buildArea: '',
          decorationArea: '',
          remarks: ''
        },
        agentUnit: {
          agentInfo: '',
          agentContact: '',
          agentPhone: ''
        },
        winningBid: {
          bidDocument: '',
          bidAmount: '',
          bidApprove: ''
        }
      },
      registrationForm: {},
      projectTypes: [],
      fileList: [],
      tableData: [],
      // 选择弹窗属性数据
      chooseDialogAttrs: {},
      projectTypeList: [],
      projectSubclassTypeList: [],
      roomId: [],
      information_rules: {
        projectName: [{ required: true, message: '请输入工程名称', trigger: 'blur' },
        { validator: validateProjectName, trigger: "blur" }],
        projectAddress: [{ required: true, message: '请输入工程地址', trigger: 'blur' }],
        projectScale: [{ required: true, message: '请输入建设规模', trigger: 'blur' }],
        projectContent: [{ required: true, message: '请输入建设内容', trigger: 'blur' }],
        projectType: [{ required: true, message: '请选择工程类型', trigger: 'change' }],
        buildArea: [{ required: false, message: '请完善关联物业以便计算建筑面积', trigger: 'blur' },
        { validator: doubleValidate, trigger: "blur" }],
        decorationArea: [{ required: true, message: '请输入装修面积', trigger: 'blur' },
        { validator: doubleValidate, trigger: "blur" }],
      },
      agentUnit_rules: {
        agentPhone: [{ required: false, message: '请输入联系电话', trigger: 'blur' },
        { validator: validatePhoneTwo, trigger: "blur" }]
      },
      winningBid_rules: {
        bidAmount: [{ required: false, message: '请输入金额', trigger: 'blur' },
        { validator: doubleValidate, trigger: "blur" }],
        bidDocument: [{ required: false, message: '请输入中标通知书文号', trigger: 'blur' },
        { validator: validateBidDo, trigger: "blur" }],
      }
    }
  },
  methods: {
    //打开弹框
    show (item) {
      this.dialogVisible = true
      if (item) {
        this.isAdd = false
        this.projectForm.information.projectId = item
        get(item).then(res => {
          if (res.data.code === 0) {
            this.projectForm.information = res.data.data.epcProject
            this.projectForm.agentUnit = res.data.data.epcProject
            this.projectForm.winningBid = res.data.data.epcProject
            this.projectForm.information.projectStart = this.projectForm.information.projectStart && this.projectForm.information.projectEnd ? [this.projectForm.information.projectStart, this.projectForm.information.projectEnd] : []
            this.tableData = res.data.data.rooms
          }
        })
      }
    },
    //关闭弹框
    beforeClose (done) {
      this.$emit('beforeClose')
    },
    //取消
    handleCancel () {
      this.$emit('handleClose')
      this.dialogVisible = false
    },
    //保存
    commit () {
      const information = new Promise((resolve, reject) => {
        this.$refs['information'].validate((valid) => {
          if (valid) {
            resolve();
          } else {
            this.$message.warning('请先完善必填信息！');
          }
        })
      })
      const agentUnit = new Promise((resolve, reject) => {
        this.$refs['agentUnit'].validate((valid) => {
          if (valid) resolve();
        })
      })
      const winningBid = new Promise((resolve, reject) => {
        this.$refs['winningBid'].validate((valid) => {
          if (valid) resolve();
        })
      })
      if (this.tableData.length === 0) {
        this.$message.error('至少关联一个物业！');
        return false;
      }
      Promise.all([information, agentUnit, winningBid]).then(() => {
        let registrationForm = {
          ...this.projectForm.information,
          ...this.projectForm.agentUnit,
          ...this.projectForm.winningBid
        }
        this.registrationForm = {
          epcProject: registrationForm,
          rooms: this.tableData
        }
        if (this.registrationForm.epcProject.projectStart) {
          const [projectStart, projectEnd] = this.registrationForm.epcProject.projectStart
          this.registrationForm.epcProject.projectStart = projectStart
          this.registrationForm.epcProject.projectEnd = projectEnd
        }
        this.$refs.registrationUpload.submit();
      })
    },
    //文件上传
    onSuccess (response, file, fileList) {
      //文件上传成功，开始保存表单
      if (fileList !== undefined && fileList.length > 0) {
        if (response.data) {
          this.registrationForm.epcProject.projectId = response.data
          this.saveFormData(response.data)
        } else {
          this.err('文件上传失败')
        }
      } else {
        this.saveFormData(response.data)
      }
    },
    saveFormData () {
      this.loadAction('数据加载中')
      if (this.isAdd) {
        save(this.registrationForm).then((rep) => {
          this.loadClose()
          this.$message.success("保存成功");
          this.dialogVisible = false
          this.$emit('resetList')
        }).catch((e) => {
          this.loadClose()
          this.$message.error("保存失败");
        })
      } else {
        update(this.registrationForm).then((rep) => {
          this.loadClose()
          this.$message.success("修改成功");
          this.dialogVisible = false
          this.$emit('resetList')
        }).catch((e) => {
          this.loadClose()
          this.$message.error("修改失败");
        });
      }
    },
    //验证中标通知书文号是否存在
    validateOnly (value, callback) {
      validateBidDocument({ "projectId": this.projectForm.information.projectId, "bidDocument": value }).then(rep => {
        let vr = rep.data.data
        if (vr === 0) {
          return callback();
        } else {
          return callback(new Error("中标通知书文号不能重复"));
        }
      })
    },
    //验证工程名称是否存在
    validateNameOnly (value, callback) {
      validateName({ "projectId": this.projectForm.information.projectId, "projectName": value }).then(rep => {
        let vr = rep.data.data
        if (vr === 0) {
          return callback();
        } else {
          return callback(new Error("工程名称不能重复"));
        }
      })
    },
    //添加关联物业
    handleAddProperty () {
      const property_types = (row, column, cellValue) => {
        if (this.projectTypeList.length === 0) return '';
        let type = this.projectTypeList.find(item => item.value == cellValue)
        return type ? type.label : ''
      };
      const property_use_types = (row, column, cellValue) => {
        if (this.projectSubclassTypeList.length === 0) return '';
        let type = this.projectSubclassTypeList.find(item => item.value == cellValue)
        return type ? type.label : ''
      };
      let arr = []
      this.tableData.map(item => {
        arr.push(item.roomId)
      })
      this.roomId = arr.filter(it => arr.indexOf(it.roomId) === -1)
      this.chooseDialogAttrs = {
        title: '选择物业',
        width: '1200px',
        placeholder: '请输入物业名称',
        url: '/api/epcproject/queryRoomPage',
        primaryKey: 'dontQueryId',
        searchKey: 'propertyName',
        multiple: true,
        defaultParams: { dontQueryId: this.roomId },
        showData: [
          { prop: 'projectName', label: '项目名称' },
          { prop: 'propertyName', label: '物业名称' },
          { prop: 'buildingArea', label: '建筑面积' },
          { prop: 'unitConstructionArea', label: '套内面积' },
          { prop: 'projectType', label: '物业类型', formatter: property_types },
          { prop: 'projectSubclassType', label: '物业用途', formatter: property_use_types }
        ]
      }
      this.$nextTick(() => {
        this.$refs.chooseDialog.show()
      })
    },
    //删除关联物业
    handleDeleteProperty (val) {
      let id = val.roomId
      this.tableData = this.tableData.filter(it => id.indexOf(it.roomId) === -1)
      this.roomId = this.roomId.filter(it => id.indexOf(it.roomId) === -1)

      this.projectForm.information.buildArea = calc.Sub(this.projectForm.information.buildArea, Number(val.buildingArea))
    },
    //工程名称确定
    handleClickAdd (arr) {
      let buildArea = this.projectForm.information.buildArea
      this.tableData = [...this.tableData, ...arr]
      arr.forEach(e => {
        buildArea = calc.Add(buildArea, Number(e.buildingArea))
      });
      this.$message.success('添加成功！')
      //this.projectForm.information.buildArea = buildArea
    },
    //对应value取label
    getCardTypeValue (num, sum) {
      let arr = sum.filter(e => e.value === num)
      if (arr.length > 0) {
        return arr[0].label
      } else {
        return num
      }
    }
  }

}
</script>

<style scoped lang='scss'>
.handling-opinions {
  padding: 20px;
  overflow: hidden;
  .add-property {
    float: right;
  }
}
</style>
